import React, { Component, Fragment } from 'react';
import './TodoList.css'

class TodoList extends Component {

  constructor(props) {
    super(props); // js 继承
    this.state = {
      inputValue: '',
      list: ['在输入框输入正在进行的内容按下并回车键', '测试一下点击右边按钮'],
      finishList: ['完成的']
    }
  }

  render () {
    return (
      <Fragment>
        <header>
          <div className="container">
            <div className="left">
              <a href="#">Yzf - TodoList</a>
            </div>
            <div className="right">
              <input 
                value={this.state.inputValue} 
                onChange={this.handleInputChange.bind(this)}
                placeholder="在此输入并回车进行增加数据操作"
                onKeyPress={this.handleEnterKey.bind(this)}
              />
            </div>
          </div>
        </header>
        <div className="wrapper">
          <div className="container">
            <div className="title">正在进行</div>
            <ul>
              {
                this.state.list.map((item, index) => {
                  return (
                    <li 
                      key={index} 
                    >
                      <span className="tag"></span>
                      {item}
                      <span className="close" onClick={this.handleItemDelete.bind(this, index)}>—</span>
                    </li>
                  )
                })
              }
            </ul>
          </div>
        </div>
        <div className="wrapper">
          <div className="container">
            <div className="title">已经完成</div>
            <ul>
              {
                this.state.finishList.map((item, index) => {
                  return (
                    <li 
                      key={index} 
                    >
                      <span className="tag finishTag"></span>
                      {item}
                    </li>
                  )
                })
              }
            </ul>
          </div>
        </div>
      </Fragment>
    )
  }

  handleInputChange(e) {
    this.setState({
      inputValue: e.target.value
    })
  }

  handleEnterKey (e) {
    if(e.nativeEvent.keyCode === 13){ //e.nativeEvent获取原生的事件对象
      this.setState({
        list: [...this.state.list, this.state.inputValue],
        inputValue: ''
      })
    }
  }

  handleItemDelete(index) {
    // immutable
    // state 不允许我们做任何的改变
    const list = [...this.state.list];

    this.setState({
      finishList: [...this.state.finishList, list[index]]
    })

    list.splice(index, 1)
    this.setState({
      list: list
    })
  }
}

export default TodoList;